package com.lan.ai.mutimodelEmbedding;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.ai.dashscope.api.ApiUtils;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.List;
import java.util.stream.Stream;

import static com.alibaba.cloud.ai.dashscope.common.DashScopeApiConstants.DEFAULT_BASE_URL;

/**
 * @author lanyanhua
 * @date 2025/1/21 14:14
 * @description
 */
public class MutimodeDashScopeApi extends DashScopeApi {
    private final RestClient restClient;

    public MutimodeDashScopeApi(String apiKey) {
//        super(apiKey);
        this(DEFAULT_BASE_URL, apiKey, RestClient.builder(), WebClient.builder(),
                RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
    }

    public MutimodeDashScopeApi(String apiKey, String workSpaceId) {
//        super(apiKey, workSpaceId);
        this(DEFAULT_BASE_URL, apiKey, workSpaceId, RestClient.builder(), WebClient.builder(),
                RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
    }

    public MutimodeDashScopeApi(String baseUrl, String apiKey, String workSpaceId) {
//        super(baseUrl, apiKey, workSpaceId);
        this(baseUrl, apiKey, workSpaceId, RestClient.builder(), WebClient.builder(),
                RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
    }

    public MutimodeDashScopeApi(String baseUrl, String apiKey, RestClient.Builder restClientBuilder, WebClient.Builder webClientBuilder, ResponseErrorHandler responseErrorHandler) {
        super(baseUrl, apiKey, restClientBuilder, webClientBuilder, responseErrorHandler);
        this.restClient = restClientBuilder.baseUrl(baseUrl)
                .defaultHeaders(ApiUtils.getJsonContentHeaders(apiKey))
                .defaultStatusHandler(responseErrorHandler)
                .build();
    }

    public MutimodeDashScopeApi(String baseUrl, String apiKey, String workSpaceId, RestClient.Builder restClientBuilder, WebClient.Builder webClientBuilder, ResponseErrorHandler responseErrorHandler) {
        super(baseUrl, apiKey, workSpaceId, restClientBuilder, webClientBuilder, responseErrorHandler);
        this.restClient = restClientBuilder.baseUrl(baseUrl)
                .defaultHeaders(ApiUtils.getJsonContentHeaders(apiKey, workSpaceId))
                .defaultStatusHandler(responseErrorHandler)
                .build();
    }


    @Override
    public ResponseEntity<EmbeddingList> embeddings(EmbeddingRequest embeddingRequest) {
        //多模态
        if (embeddingRequest.model().equals("multimodal-embedding-v1")) {

//            MutimodelEmbeddingRequest request = MutimodelEmbeddingRequest.of("multimodal-embedding-v1",
//                    MutimodelEmbeddingRequest.contents("金毛", getBase64Image("jpg", "/Users/lanyanhua/Downloads/gou111.jpg"), "")
////                MutimodelEmbeddingRequest.contents("阿迪帽子", "https://mitalinlp.oss-cn-hangzhou.aliyuncs.com/dingkun/images/1712648554702.jpg", "")
//            );
            List<MutimodelEmbeddingRequest.Contents> inputContents = embeddingRequest.input().texts().stream().flatMap(text -> {
                try {
                    return JSONUtil.toBean(text, new TypeReference<List<MutimodelEmbeddingRequest.Contents>>() {
                    }, false).stream();
                } catch (Exception e) {
                    return Stream.of(new MutimodelEmbeddingRequest.Contents() {{
                        setText(text);
                    }});
                }
            }).toList();
            MutimodelEmbeddingRequest request = new MutimodelEmbeddingRequest() {{
                setModel(embeddingRequest.model());
                setInput(new MutimodelEmbeddingRequest.Input() {{
                    setContents(inputContents);
                }});
            }};
            ResponseEntity<EmbeddingList> entity = restClient.post()
                    .uri("/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding")
                    .body(request)
                    .retrieve()
                    .toEntity(EmbeddingList.class);
            EmbeddingList body = entity.getBody();
            assert body != null;
            EmbeddingList embeddingList = new EmbeddingList(body.requestId(), body.code(), body.message(), body.output(), new EmbeddingUsage(0L));
            return new ResponseEntity<>(embeddingList, entity.getHeaders(), entity.getStatusCode());
        }
        return super.embeddings(embeddingRequest);
    }
//
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    public record MutimodelEmbeddingRequestInput(
//            @JsonProperty("contents") List<MutimodelEmbeddingRequestInputContent> contents) {
//
//    }
//
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    public record MutimodelEmbeddingRequestInputContent(@JsonProperty("text") String text,
//                                                        @JsonProperty("image") String image
//            , @JsonProperty("vedio") String vedio) {
//        public MutimodelEmbeddingRequestInputContent(String text) {
//            this(text, null, null);
//        }
//    }
//
//    /**
//     * Creates an embedding vector representing the input text.
//     */
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    public record MutimodelEmbeddingRequest(@JsonProperty("model") String model,
//                                            @JsonProperty("input") MutimodelEmbeddingRequestInput input) {
//
//    }

}
